import os.path
import zipfile

import requests
from requests.utils import requote_uri

from .crc import get_crc64


def download(url, filename, unzip=False):
    with open(filename, "wb") as f:
        file_resp = requests.get(requote_uri(url), stream=True, timeout=30)
        print(f"Downloading {filename}")
        if file_resp.status_code == 200:
            for chunk in file_resp.iter_content(1024):
                f.write(chunk)
            print(f"Downloaded {filename}")
        else:
            print(f"Failed to download {filename} {file_resp.status_code}")

    # 校验crc
    cos_crc64 = file_resp.headers.get('X-Cos-Hash-Crc64ecma')
    if cos_crc64:
        cos_crc64 = int(cos_crc64)
        computed_crc = get_crc64(filename)
        if cos_crc64 != computed_crc:
            raise RuntimeError("文件校验错误")
    # 解压
    if unzip:
        path = os.path.split(filename)[0]
        with zipfile.ZipFile(filename, "r") as f:
            f.extractall(path)
        os.remove(filename)
